import tushare as ts
import pandas as pd
#李爽李爽李爽
# 初始化pro接口
pro = ts.pro_api('7705d187ddde476492fc7c72b674218f8d383448f7126a0457392231')

# 获取最近10个交易日的日期
trade_days = pro.trade_cal(start_date='20230101', end_date='20231020', is_open='1')
trade_days = trade_days['cal_date'].tolist()[-10:]

# 获取所有股票的日线数据
all_stocks_daily_data = []

for ts_code in pro.stock_basic()['ts_code']:
    daily_data = pro.daily(ts_code=ts_code, start_date=trade_days[0], end_date=trade_days[-1])
    daily_data['ts_code'] = ts_code  # 添加股票代码
    all_stocks_daily_data.append(daily_data)

# 合并所有股票数据
df = pd.concat(all_stocks_daily_data, ignore_index=True)

# 统计表
stats = df.describe()
print(stats)


def calculate_indicators(df):
    # 按 ts_code 分组计算技术指标
    df['close'] = df['close'].astype(float)  # 确保价格为浮动类型
    df['ma5'] = df.groupby('ts_code')['close'].transform(lambda x: x.rolling(window=5).mean())
    df['ma10'] = df.groupby('ts_code')['close'].transform(lambda x: x.rolling(window=10).mean())

    # 计算 RSI
    delta = df['close'].diff(1)
    gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
    rs = gain / loss
    df['rsi'] = 100 - (100 / (1 + rs))

    return df


# 计算技术指标
df_with_indicators = calculate_indicators(df)
# 提取买点股票
buy_signals = df_with_indicators[(df_with_indicators['ma5'] > df_with_indicators['ma10']) &
                                  (df_with_indicators['ma5'].shift(1) <= df_with_indicators['ma10'].shift(1))]

# 获取符合条件的股票列表
buy_stock_list = buy_signals[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']]
print(buy_stock_list)